package com.yituo.mjworld.mvc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.core.utils.OtherTool;
import com.yituo.mjworld.core.web.core.BaseForm;
import com.yituo.mjworld.core.web.core.Result;
import com.yituo.mjworld.mvc.dao.UserDao;
import com.yituo.mjworld.mvc.entity.other.RecordAgentRequest;
import com.yituo.mjworld.mvc.entity.web.UserRole;
import com.yituo.mjworld.mvc.entity.web.WebUser;
import com.yituo.mjworld.mvc.entity.web.WebUserQrcode;
import com.yituo.mjworld.mvc.form.DeleteForm;
import com.yituo.mjworld.mvc.form.QueryForm;
import com.yituo.mjworld.mvc.form.support.user.Login;
import com.yituo.mjworld.mvc.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 超级管理员的模块
 */
@Service
public class AdminServiceImpl extends BaseService {
  @Autowired
  UserServiceImpl userService;
  @Autowired
  UserDao userDao;

  @Override
  public JSONObject getList(QueryForm form) {
    return null;
  }

  @Override
  public Result delete(DeleteForm form) {
    return null;
  }


  /**
   * 保存或者新增用户
   *
   * @param baseForm 更新表单
   * @return
   */
  @Override
  public Result saveOrUpdate(BaseForm baseForm) {
    Result result = new Result();
    WebUser user = (WebUser) baseForm;
    WebUser user_db = (WebUser) baseDao.get(WebUser.class, user.getId());
    WebUser user_db2 = userDao.getUserByAccount(user.getAccount());
    if (user_db == null) {
      // 新增
      if (user_db2 == null) {
        // 无重复帐号
        baseDao.saveOrUpdate(user);
        return result.setResult(true);
      } else {
        return result.setResult(false).setMsg("帐号名重复!请重新输入!");
      }
    } else {
      if (user_db2 == null) {
        BeanUtils.copyProperties(user_db, user.getParam());
        // 无重复帐号
        baseDao.merge(user);
        return result.setResult(true);
      } else {
        if (!user.getId().equals(user_db2.getId())) {
          return result.setResult(false).setMsg("帐号名重复!请重新输入!");
        } else {
          BeanUtils.copyProperties(user_db, user.getParam());
          baseDao.merge(user);
        }
      }
    }
    return result.setResult(true);
  }

  /**
   * 登录
   *
   * @param form
   * @return
   */
  public WebUser login(Login form) {
    Map<String, Object> params = new HashMap<String, Object>();
    List<WebUser> list = baseDao.findByHql("from WebUser", params);
    if (list != null && list.size() > 0) {
      return (list.get(0));
    } else {
      return null;
    }
  }

  /**
   * 更新密码
   *
   * @param newPassword
   * @return
   */
  public boolean updatePassword(String accounts, String newPassword) {
    WebUser admin = (WebUser) baseDao.get(WebUser.class, accounts);
    if (admin != null) {
      admin.setPassword(newPassword);
      baseDao.saveOrUpdate(admin);
      return true;
    }
    return false;
  }

  /**
   * 创建用户
   *
   * @param currentUser
   * @param newUser
   * @return
   */
  public Result createUser(WebUser currentUser, WebUser newUser) {
    Result result = new Result();
    if (userDao.accountsIsExits(newUser.getAccount())) {
      return result.setResult(false).setMsg("帐号已经存在!请重新输入");
    }
    if (UserRole.isSuperAdmin(currentUser)) {
      // 超级管理员手动只开放创建省级代理的权限
      newUser.setRegisterDate(new Date());
      newUser.setReferrer(currentUser.getId());
      newUser.setRule(UserRole.PRO_AGENT);
      newUser.setId(OtherTool.getUUID());
      // 保存省级代理
      baseDao.saveOrUpdate(newUser);
      // 创建用户的二维码并获取到对应的七牛图片URL
      String qrCodeUrl = userService.getUserQrcode(newUser.getId());
      if (StringUtils.isEmpty(qrCodeUrl)) {
        return result.setResult(false).setMsg("二维码生成失败!");
      }
      WebUserQrcode qrcode = new WebUserQrcode();
      qrcode.setQrCode(qrCodeUrl);
      qrcode.setCreateDate(new Date());
      qrcode.setStatus(true);
      qrcode.setUserId(newUser.getId());

      // 保存二维码
      baseDao.saveOrUpdate(qrcode);
      return new Result().setResult(true);

    }
    return new Result().setResult(false).setMsg("创建代理失败");
  }

  /**
   * 申请成为代理
   *
   * @return
   */
  public Result requestAgent(WebUser currentUser, WebUser parentUser) {
    Result result = new Result();
    // 如果是代理级别的话,都需要申请并等待其上级代理通过.
    if (UserRole.isAgent(parentUser)) {
      RecordAgentRequest record = new RecordAgentRequest();
      record.setRequestDate(new Date());
      record.setRequestUserId(currentUser.getId());
      record.setParentId(parentUser.getId());
      record.setProcessStatus(RecordAgentRequest.STATUS_WAIT);
      this.baseDao.save(record);
      return result.setResult(true).setMsg("正在等待系统审核您的资质,");
    } else {
      return result.setResult(true).setMsg("您的帐号由于特殊原因,无法申请成为代理!");
    }
  }

  /**
   * 处理请求
   *
   * @return
   */
  public Result processRueqest(int recordId, int processStatus, String processMsg, String processUserId) {
    Result result = new Result();
    RecordAgentRequest record = (RecordAgentRequest) baseDao.get(RecordAgentRequest.class, recordId);
    if (record == null) {
      return result.setResult(false).setMsg("记录不存在");
    } else {
      if (processStatus == RecordAgentRequest.STATUS_PASS) {
        WebUserQrcode qrcode = userService.getUserQrCodeInfo(record.getRequestUserId());
        if (qrcode != null) {
          result.setResult(false).setMsg("该用户已经申请过了二维码了!不可重复申请!");
        }
        String qrCodeUrl = userService.getUserQrcode(record.getRequestUserId());
        if (StringUtils.isEmpty(qrCodeUrl)) {
          return result.setResult(false).setMsg("用户申请的二维码生成失败!请重新尝试!");
        }
        WebUserQrcode webUserQrcode = new WebUserQrcode();
        webUserQrcode.setQrCode(qrCodeUrl);
        webUserQrcode.setCreateDate(new Date());
        webUserQrcode.setUserId(record.getRequestUserId());
        webUserQrcode.setStatus(true);
        baseDao.save(webUserQrcode);
      }
      record.setProcessStatus(processStatus);
      record.setProcessMsg(processMsg);
      record.setProcessDate(new Date());
      record.setProcessUserId(processUserId);
      baseDao.update(record);
      return result.setResult(true).setMsg("");
    }
  }
}
